#include "requesttask.h"
//#include <QThreadPool>


RequestTask::RequestTask(QObject *parent)
    : QObject{parent}
{
    tcpSocket = new QTcpSocket(this);
    m_recvBuffer.clear();
    connect(tcpSocket, &QTcpSocket::readyRead, this, &RequestTask::handleResponse);
    connect(tcpSocket, &QTcpSocket::errorOccurred, this, &RequestTask::socketError);
}

RequestTask::~RequestTask()
{
    //qDebug()<<"~RequestTask()"<<m_reqParam;
}

void RequestTask::start()
{
    //qDebug()<<"start thread"<<m_reqParam;

    sendRequest(m_sendMsg); // 替换为实际要发送的消息
}

void RequestTask::sendRequest(const QString &message)
{
    //qDebug()<<"connectToHost"<<m_reqParam<<m_address<<m_port<<message;
    QString proxyStr = g_proxyPool.getNextProxy();
    //qDebug()<<"get proxy"<<proxyStr;
    QStringList stringList = proxyStr.split(":");
    QNetworkProxy socks5Proxy(
        QNetworkProxy::Socks5Proxy,
        stringList.at(0),
        stringList.at(1).toInt()
        );
    qDebug()<<socks5Proxy;
    tcpSocket->setProxy(socks5Proxy);
    tcpSocket->connectToHost(this->m_address, m_port); // 替换为实际的服务器地址和端口
    if (!tcpSocket->waitForConnected()) {
        qWarning() << "Failed to connect to server";
        return;
    }
    //qDebug()<<"sendRequest"<<m_reqParam<<message;
    tcpSocket->write(message.toUtf8() + "\n");
    tcpSocket->flush();
}

void RequestTask::handleResponse()
{
    while (tcpSocket->bytesAvailable())
    {
        m_recvBuffer += tcpSocket->readAll();
        //qDebug()<<"handleResponse"<<m_reqParam<<m_recvBuffer.length();
    }

    //QByteArray response = tcpSocket->readAll();
    //    emit responseReceived(m_recvBuffer);
    //    deleteLater();
}
void RequestTask::socketError(QAbstractSocket::SocketError error)
{

    switch (error) {
    case QAbstractSocket::RemoteHostClosedError:
        if(m_recvBuffer.length())//有数据才发送信息进行处理
        {
            emit responseReceived(m_recvBuffer,m_reqParam);
            //qDebug() << "emit responseReceived"<<m_reqParam<<m_recvBuffer.length();
            //qDebug() <<m_recvBuffer;
        }
        break;
    default:
        qWarning() << "other socketError" << m_reqParam<<error;
        break;
    }
    deleteLater();
    //emit errorOccurred(tcpSocket->errorString());
}
